<template>
  <Drawer
    :visible="props.visible"
    :title="props.title"
    :width="drawerWidth"
    :modal="drawerModal"
    @close="closeDrawer"
  >
    <template #drawer-content>
      <el-form
        :model="skuForm"
        :rules="rules"
        label-width="auto"
        ref="sku"
        style="max-width: 600px; margin: auto"
      >
        <el-form-item label="SKU名称" prop="skuName">
          <el-input v-model="skuForm.skuName" placeholder="请输入SPU名称" />
        </el-form-item>
        <el-form-item label="价格(元)" prop="price">
          <el-input-number
            v-model="skuForm.price"
            :precision="2"
            placeholder="请输入价格"
          />
        </el-form-item>
        <el-form-item label="重量(克)">
          <el-input-number
            v-model="skuForm.weight"
            :precision="2"
            placeholder="请输入重量"
          />
        </el-form-item>
        <el-form-item label="SKU描述">
          <el-input
            v-model="skuForm.skuDesc"
            type="textarea"
            :rows="2"
            placeholder="请输入SKU的描述"
          />
        </el-form-item>
        <el-form-item label="平台属性">
          <el-form :inline="true" label-width="auto">
            <el-form-item
              :label="item.attrName"
              v-for="item in attrArr"
              :key="item.id"
            >
              <el-select
                v-model="item.attrIdAndValueId"
                placeholder="请选择"
                style="width: 150px; margin-bottom: 10px"
              >
                <el-option
                  v-for="o in item.attrValueList"
                  :key="o.id"
                  :label="o.valueName"
                  :value="`${item.id}:${o.id}`"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </el-form-item>
        <el-form-item label="销售属性">
          <el-form :inline="true" label-width="auto">
            <el-form-item
              :label="item.saleAttrName"
              v-for="item in saleAttr"
              :key="item.id"
            >
              <el-select
                v-model="item.saleIdAndValueId"
                placeholder="请选择"
                style="width: 150px; margin-bottom: 10px"
              >
                <el-option
                  v-for="o in item.spuSaleAttrValueList"
                  :key="o.id"
                  :label="o.saleAttrValueName"
                  :value="`${item.id}:${o.id}`"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </el-form-item>
        <el-form-item label="图片名称">
          <el-table :data="tableData" :border="true" max-height="400px">
            <el-table-column prop="imgUrl" label="图片">
              <template #default="{ row }">
                <img :src="row.imgUrl" style="width: 100px; height: 100px" />
              </template>
            </el-table-column>
            <el-table-column prop="imgName" label="名称" width="150" />
            <el-table-column prop="action" label="操作" width="120">
              <template #default="{ row }">
                <el-button
                  :type="row.default ? 'success' : 'primary'"
                  @click="setDefaultImg(row)"
                >
                  {{ row.default ? '默认图片' : '设置默认' }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
    </template>
    <template #drawer-footer>
      <el-space wrap>
        <el-button type="primary" @click="saveSku">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-space>
    </template>
  </Drawer>
</template>

<script setup lang="ts" name="Sku">
import { ref, withDefaults, watch } from 'vue'
import { reqSpuSaleAttr, reqSpuImage, addSkuReq } from '@/api/product/spu'
import { reqCategoryList } from '@/api/product/attr'
import { ElMessage } from 'element-plus'

interface Props {
  visible: boolean
  title: string
  data: any
  objId: any
}

interface Emits {
  (event: 'success', isShow: boolean): void
  (event: 'closeDrawer', isShow: boolean): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  title: '添加SKU',
  data: () => {
    {
      return {}
    }
  },
  objId: () => {
    {
      return {}
    }
  }
})

watch(
  () => props.visible,
  val => {
    if (val) {
      const subData = JSON.parse(JSON.stringify(props.data))
      let { id, tmId, category3Id } = subData
      skuForm.value.spuId = id
      skuForm.value.tmId = tmId
      skuForm.value.category3Id = category3Id
      getCategoryData()
      getSpuImage(props.data.id)
      getSpuSaleAttr(props.data.id)
    }
  }
)

let drawerWidth = ref(800)
let drawerModal = ref(true)
let saleAttr = ref<any>([])
let attrArr = ref<any>([])
let tableData = ref<any>([])
let skuForm = ref<any>({
  category3Id: '',
  spuId: '',
  skuName: '',
  tmId: '',
  price: 0,
  weight: 0,
  skuDesc: '',
  skuAttrValueList: [], // 平台属性
  skuSaleAttrValueList: [], // 销售属性
  skuDefaultImg: '' // 默认图片
})
let rules = {
  skuName: { required: true, message: 'SKU名称不能为空', trigger: 'blue' },
  price: { required: true, message: '价格不能为空', trigger: 'blue' }
}
const emits = defineEmits<Emits>()
const sku = ref()

const getCategoryData = async () => {
  let res: any = await reqCategoryList(
    props.objId.c1,
    props.objId.c2,
    props.data.category3Id
  )
  if (res.code === 200) {
    attrArr.value = res.data
  } else {
    ElMessage.error(res.message)
  }
}

// 查询已有的销售属性
const getSpuSaleAttr = async (spuId: any) => {
  let res: any = await reqSpuSaleAttr(spuId)
  if (res.code === 200) {
    saleAttr.value = res.data
  } else {
    ElMessage.error(res.message)
  }
}

//查询商品图片
const getSpuImage = async (spuId: any) => {
  let res: any = await reqSpuImage(spuId)
  if (res.code === 200) {
    tableData.value = res.data
  } else {
    ElMessage.error(res.message)
  }
}

// 设置默认图片
const setDefaultImg = (data: any) => {
  tableData.value.forEach((item: any) => {
    item.default = false
  })
  data.default = true
  skuForm.value.skuDefaultImg = data.imgUrl
}

// 保存方法
const addSKu = async (data: any) => {
  let isAdd = data.id ? false : true
  let res: any = await addSkuReq(data)
  if (res.code === 200) {
    ElMessage.success(res.message)
    emits('success', false)
  } else {
    ElMessage.error(res.message)
  }
}

// 保存
const saveSku = async () => {
  await sku.value.validate(async (valid: any) => {
    if (valid) {
      skuForm.value.skuAttrValueList = attrArr.value.reduce(
        (prev: any, next: any) => {
          if (next.attrIdAndValueId) {
            const [attrId, valueId] = next.attrIdAndValueId.split(':')
            prev.push({
              attrId,
              valueId
            })
          }
          return prev
        },
        []
      )
      skuForm.value.skuSaleAttrValueList = saleAttr.value.reduce(
        (prev: any, next: any) => {
          if (next.saleIdAndValueId) {
            const [saleAttrId, saleAttrValueId] =
              next.saleIdAndValueId.split(':')
            prev.push({
              saleAttrId,
              saleAttrValueId
            })
          }
          return prev
        },
        []
      )
      addSKu(skuForm.value)
    }
  })
}

// 取消
const cancel = () => {
  emits('closeDrawer', false)
}

// drawer 关闭回调
const closeDrawer = (value: boolean) => {
  emits('closeDrawer', value)
}
</script>

<style scoped></style>
